var platformSeries=[
    {name:'当前总用气',type:'line',lineStyle:'solid',color:'#00ccfe'},
    {name:'预计总用气',type:'line',lineStyle:'dotted', color:'#00ccfe'},
    {name:'1号锅炉用气',type:'line',lineStyle:'solid',color:'#88c512'},
    {name:'2号锅炉用气',type:'line',lineStyle:'solid',color:'#6a20e7'},
    {name:'3号锅炉用气',type:'line',lineStyle:'solid',color:'#8b05c6'},
    {name:'4号锅炉用气',type:'line',lineStyle:'solid',color:'#b56911'},
    {name:'5号锅炉用气',type:'line',lineStyle:'solid',color:'#1a8cff'}
];
var platformOption={
    tooltip:{
        show:true,
        formatter:function(params){
            var nameArr = [];
            var valueArr = [];
            var str = '';
            for(var i=0;i<params.length;i++){
                nameArr[i]=params[i].seriesName;
                valueArr[i]=Number(params[i].data).toFixed(1);

                str+= nameArr[i]+' : '+valueArr[i]+'<br/>'
            }
            return str
        }
    },
    yAxis:{
        name:'X10³',
        axisLabel:{
            formatter:function (value, index) {
                return Number(value)/Math.pow(10,3).toFixed(1);
            }
        }
    }
};
var barChart ={
    title: {
        text: ''
    },
    tooltip: {
        trigger: 'axis',
        axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
        }
    },
    legend: {
        show:false
    },
    grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    },
    xAxis: [{
        type: 'category',
        data: ['超上限时长', '超下限时长', '正常时长'],
        axisLine:{
            lineStyle:{
                color:'#b0e9fe'
            }
        },
    }],
    yAxis: [{
        type: 'value',
        name: '时长（分钟）',
        axisLine:{
            lineStyle:{
                color:'#b0e9fe'
            }
        },
        axisLabel: {
            formatter: '{value}'
        },
        splitLine:{
            show:false
        }
    }],
    series: [{
        name: '数值',
        type: 'bar',
        itemStyle:{
            normal:{
                color:'#04321e',
                borderColor: '#078d1c',
                borderWidth: 1,
            }
        },
         data:[]
        // data: [20,25,35]
    },
        /*{
         name: '下限值',
         type: 'bar',
         itemStyle:{
         normal:{
         color:'#3a321b',
         borderColor: '#e08f0f',
         borderWidth: 1,
         }
         },
         // data:[]
         data: [10]
         }, {
         name: '正常',
         type: 'bar',
         itemStyle:{
         normal:{
         color:'#37161b',
         borderColor: '#d31d11',
         borderWidth: 1,
         }
         },
         //data:[]
         data: [1]
         }*/]
};



//消息中心
Vue.component('my-message',
    {
        props:['msg'],
        data:function(){
            return {
                width:'',
                message:this.msg,
                canceldata:false,
                currIndex:0,
                resonList:[],
                reasonVal:'',
                subId:'',
                timeStamp:0
            }
        },
        mounted:function(){
            var _this=this;
            this.$nextTick(function(){
                _this.getTimeStamp();
                setInterval(function(){
                    _this.getTimeStamp();
                },1000*60)

            })
        },
        template:`
        <div>
            <ul class="content-list" id="content_list">
                <li class="content-item conent-list-li clearfix" :class="[timeStamp-item.start_time<300000?'backgroundR':'']" v-for="(item,index) in msg">
                    <p class="content-name fl w200 mr2">
                           【{{item.device_name}}】{{item.title}}
                   </p>
                    <p class="content-descrbie fl w100 mr2">{{item.start_time |formatterTime}}</p>
                    <p class="content-ascription fl w120 mr2">{{item.prediction|formatterVal|keepTwo}}x10<sup>4</sup>m<sup>3</sup>/h</p>
                    <div class="fl content-status">
                        <div class="content-prediction-scroll">
                        {{item.description}}
                        </div>
                    </div>
                    <p class="content-operate fl w76">
                        <!--<a href="javascript:;" class="content-operate-msg"></a>-->
                        <a href="javascript:;" class="content-operate-close" v-show="item.cancelable" @click="cancel(item,index)"></a></p>
                    <div class="cancel-popup border"  v-show="canceldata">
                        <span>操作人 </span> ：&nbsp&nbsp<select name="" id="" class="can-select border">
                        <option value="" v-for="reason in resonList" >{{reason.content}}</option>  
                    </select>
                        </br>
                        <span>取消原因</span>：<select name="" id="" class="can-select border" @change="getVal" v-model="reasonVal">
                        <option value="" v-for="reason in resonList" :value="reason.id">{{reason.content}}</option>
                    </select>
                        <div class="clearfix can-tip">
                            <p class="fl can-button can-icon border" @click="dis">取消</p>
                            <p class="fl can-button can-define border" @click="define(currIndex)">确定</p>
                        </div>
                    </div>
                </li>
            </ul>
        </div>   
        `,
        filters:{
            substr:function(val){
                return (val).substring(4);
            },
            substrName:function(val){
                return (val).substring(0,4)
            },
            formatterTime:function(val){
                var val=Math.abs(val);
                var date=new Date(val);
                var month=date.getMonth()+1;
                var day=date.getDate();
                var hour=date.getHours();
                var min=date.getMinutes();
                return toDou(month)+"-"+toDou(day)+" "+toDou(hour)+":"+toDou(min);
            },
            keepTwo:function(val){
                return val.toFixed(2);
            },
            formatterVal:function(val){
                var val=Math.abs(val);
                return val/Math.pow(10,4)
            }
        },
        methods:{
            getVal:function(){

            },
            /*信息取消*/
            cancel:function(item,index){
                this.currIndex=index;
                this.canceldata=true;
                var type=item.type;
                this.subId=item.sub_evt_id;
                var success=function(res){
                    this.resonList=res.data;
                    this.reasonVal=this.resonList[0].id;
                };
                var error=function(e){
                    console.log('取消事件原因出错了')
                };
                this.$http.get(URL+'/event/reason/'+type).then(success,error);
            },
            /*弹出框取消*/
            dis:function(){
                this.canceldata=false;
            },
            /*弹出框确认*/
            define:function(index){
                this.canceldata=!this.canceldata;
                this.message.splice(index,1);
                var success=function(res){};
                var error=function(e){
                    console.log('弹出框确定出错了')
                };
                this.$http.post(URL+'/message/cancellation',{sub_evt_id:this.subId,reason:this.reasonVal}).then(success,error);

            },
            getTimeStamp:function(){
                var _this=this;
                var success=function(res){
                    _this.timeStamp=res.data.time;
                    //console.log(res.data);
                };
                var error=function(e){
                    console.log('加载时间戳出错了');
                };

                this.$http.get(URL+'/time/getTime').then(success,error);
            }

        }
    });

var statusChartData=[
    {
        name:'pressure',
        series:[
            //{name:'锅炉支管压力预测',type:'line',lineStyle:'solid',color:'#00ccfe'},
            {name:'3#TRT压力历史',type:'line',lineStyle:'solid',color:'#00ccfe'}


        ]
    },
    {
        name:'gas',
        series:[
            {name:'锅炉用气预测',type:'line',lineStyle:'dotted',color:'#00ccfe'},
            {name:'锅炉用气历史',type:'line',lineStyle:'solid',color:'#00ccfe'}
        ]
    }
];
var  gasOption=[

    {
        tooltip:{
            show:true,
            formatter:function(params){
                var nameArr = [];
                var valueArr = [];
                var str = '';
                for(var i=0;i<params.length;i++){
                    nameArr[i]=params[i].seriesName;
                    valueArr[i]=Number(params[i].data).toFixed(1);
                    str+= nameArr[i]+' : '+valueArr[i]+'<br/>'
                }
                return str
            }
        },
        grid:{
            left:60,
            top:60,
            right:30,
            bottom:30
        },
        yAxis:{
            name:'压力(kPa)'
        }
    },{
        tooltip:{
            show:true,
            formatter:function(params){
                var nameArr = [];
                var valueArr = [];
                var str = '';
                for(var i=0;i<params.length;i++){
                    nameArr[i]=params[i].seriesName;
                    valueArr[i]=Number(params[i].data).toFixed(1);

                    str+= nameArr[i]+' : '+valueArr[i]+'<br/>'
                }
                return str
            }
        },
        grid:{
            left:60,
            top:60,
            right:30,
            bottom:30
        },
        yAxis:{
            name:'X10⁴',
            axisLabel:{
                formatter:function (value, index) {
                    return Number(value)/Math.pow(10,4).toFixed(1);
                }
            }
        }
    }
];
//锅炉图表
var guoluapp =new Vue({
    el:'#app',
    data:{
        headerMenuList:[
            ['1号锅炉','1'],
            ['2号锅炉','2'],
            ['3号锅炉','3'],
            ['混烧4号锅炉','4'],
            ['混烧5号锅炉','5']
        ],
        currentData:{
            current_pressure:0,
            predict_pressure:1,
            current_flow:2,
            predict_flow:3
        },
        statusChart:[],
        statusChartId:['chart_'+uuid(8,64),'chart_'+uuid(8,64)],
        barChartId:['chart_'+uuid(8,64)],
        historyData:{},
        guolu:3,
        platformChart:null,
        platformHistory:{},
        timedata:3600000,//选择时间
        msglist:[],
        isActive:true,
        coordination:[],
        gasPrediction:0,//右侧系统同台数据
        gasCurrent:'',//右侧系统同台数据
        currentStatus:false,
        Achievements:{},
        msgType:'all',
        fangsanReal:0
    },
    filters:{
        keepTwo:function(val){
            return (val/Math.pow(10,3)).toFixed(2);
        },
        setfive:function(val){
            return (val/Math.pow(10,5)).toFixed(2);
        },
        Percentage:function(val){
          return   (val*100).toFixed(2);
        },
        toCn:function(val){
            switch(val){
                case 0:
                    return '3号TRT压力';
                    break;
                case 1:
                    return '锅炉用气';
                    break;
            }
        },
        toStatus:function (val) {
            switch (val){
                case 0:
                   return '未达满负荷';
                   break;
                case 1:
                    return '需要调节';
                    break;
                case 2:
                    return '停炉';
                    break;
                case 3:
                    return '满负荷生产';
                    break;
                case 4:
                    return '低于正常工作下限';
                    break;
                case 5:
                    return '所有锅炉达到调节极限';
                    break;
            }
        }

    },
    mounted:function(){
        this.$nextTick(function () {
            this.showTime();
            this.getmessdata();
            this.getGuoluNum();
            this.updateGuolu();
            this.getCoordination();
            this.getCurrentgas();
            this.initBarChart();
            this.getRealPoint();
            var _this= this;
            setTimeout(function(){
                _this.initchart();
                _this.loadStatusChartHistoryData();
                _this.loadStatusChartRealData();
                //协同台
                _this.initPlatFormChart();
                _this.getPlatFormHistory();
                _this.getPlatFormReal();
                _this.getCurrentgas();
                _this.getBarchart();
            },2000);
            setInterval(function(){
                _this.loadStatusChartRealData();
                //协同台
                //加载预测暂时没数据
                _this.getPlatFormChartData({
                    name:'预计总用气',
                    type:'prediction',
                    url:URL+'/quanwang/guolu/prediction'
                });
                _this.getPlatFormReal();
                _this.getCoordination();//锅炉协同
                _this.getmessdata();
                _this.getBarchart();
                _this.getRealPoint();//平均放散开度
            },3000)
        })
    },
    methods:{
        updateGuolu:function(){
            var item=getStore('guolu');
            if(item){
                this.guolu=item[1];
            }
        },
        getGuoluNum:function(){
            var _this=this;
            bus.$on('num',function(num){
                _this.guolu=num;
                _this.loadStatusChartHistoryData();
                //_this.loadStatusChartRealData();
            })
        },
        showTime:function () {
          var _this = this;
          bus.$on('name',function (val){
              _this.timedata = val;
          })
        },
        initchart:function(){
            var _this=this;
            this.statusChartId.forEach(function(item,index){
                var _index = index;
                _this.statusChart[index]=new Chart(item,{
                    data:statusChartData[_index].series,
                    baseOption:gasOption[_index]
                })
            });
        },
        getSeriesName:function(progress,type){
            var seriesName='';
            if(type=='history' || type=='realPoint'){
                switch(progress){
                    case 'pressure':
                        seriesName='3#TRT压力历史';
                        break;
                    case 'gas':
                        seriesName='锅炉用气历史';
                        break;
                }
            }else if(type=='prediction'){
                switch(progress){
                    case 'gas':
                        seriesName='锅炉用气预测';
                        break;
                }
            }

            return seriesName;
        },
        getStatusChartData:function(progress,type,index){
            var success = function (res) {
                var _this= this;
                var data = res.data;
                var seriesName =_this.getSeriesName(progress,type)
                var axis = getAxis(data);
                if(type=='prediction'){
                    if(axis.dataX.length==0) return;
                    var predictData = axis.dataX;
                    if(seriesName=='锅炉用气预测'){
                        _this.statusChart[index].loadX(axis.dataX);
                        //获取实时的点：预测的最后一个点
                        _this.currentData.predict_flow=(Number(axis.dataY[axis.dataY.length-1])/Math.pow(10,3)).toFixed(2);
                    }

                    /*switch(seriesName){
                        /!*case '锅炉支管压力预测':
                        _this.currentData.predict_pressure=(Number(axis.dataY[axis.dataY.length-1])).toFixed(2);
                        break;*!/
                        case '锅炉用气预测':
                        _this.currentData.predict_flow=(Number(axis.dataY[axis.dataY.length-1])/Math.pow(10,3)).toFixed(2);
                        break;
                    }*/
                }
                if(type=='history'){
                    _this.historyData[progress+'_'+type]=data;
                    if(seriesName=='3#TRT压力历史'){//没有预测以历史数据为X轴
                        _this.statusChart[index].loadX(axis.dataX);
                        //_this.statusChart[index].loadData(seriesName,axis.dataY)
                    }
                }
                if(type=='baseLine'){
                    //if(data.length==0) return;//调代码
                    _this.statusChart[index].loadBaseLine(seriesName,{
                        data:data
                    })
                }
                if(type=='realPoint'){
                    if(!_this.historyData[progress+'_history']) return;
                    _this.historyData[progress+'_history'].shift();
                    _this.historyData[progress+'_history'].push(data);
                    axisreal = getAxis(_this.historyData[progress+'_history']);
                    //获取实时的点：每一个点
                    switch(seriesName){
                        case '3#TRT压力历史':
                            _this.currentData.current_pressure=Number(data[1]).toFixed(2);
                            _this.statusChart[index].loadX(axisreal.dataX);
                            break;
                        case '锅炉用气历史':
                            _this.currentData.current_flow=(Number(data[1])/Math.pow(10,3)).toFixed(2);
                            break;
                    }
                    _this.statusChart[index].loadData(seriesName,axisreal.dataY);

                }else{
                    _this.statusChart[index].loadData(seriesName,axis.dataY)
                }
            };
            var error = function(e){
                console.log(progress+'加载锅炉'+type+'图表出错了')
            };
            this.$http.get(URL+'/guolu/'+this.guolu+'/'+progress+'/'+type).then(success,error);
        },
        loadStatusChartHistoryData:function(){
            for(var i=0;i<statusChartData.length;i++){
                var name=statusChartData[i].name;
                this.getStatusChartData(name,'history',i);
                this.getStatusChartData(name,'baseLine',i);
            }
        },
        loadStatusChartRealData:function(){
            for(var i=0;i<statusChartData.length;i++){
                var name=statusChartData[i].name;
                if(name=='pressure'){
                    this.getStatusChartData(name,'realPoint',i);
                }else if(name=='gas'){
                    this.getStatusChartData(name,'prediction',i);
                    this.getStatusChartData(name,'realPoint',i);
                }

            }
        },
        getmessdata:function(){
            /*
            * 信息中心交互
            * */
            var _this=this;
            var success = function(res){
                 _this.msglist = res.data
            };
            var error = function(e){
                console.log('信息加载错误')
            };
            this.$http(URL+'/message/current').then(success,error);
        },
        setHistorydata:function(){
            /*设置cooking 存锅炉信息*/
            setStore('furnace','guolu')
        },
        initPlatFormChart:function(){
            this.platformChart=new Chart('guolu_platform_chart',{
                data:platformSeries,
                baseOption:platformOption
            })
        },
        getPlatFormChartData:function(config){
            var _this=this;
            var success=function(res){
                var data=res.data;
                var Axis=getAxis(data);
                if(config.type=='prediction'){//预测
                    _this.platformChart.loadX(Axis.dataX);
                    _this.platformChart.loadData('预计总用气',Axis.dataY);
                    _this.gasPrediction=Axis.dataY[Axis.dataY.length-1];
                }else if(config.type=="history"){//历史
                    _this.platformHistory[config.name+'_'+config.type]=Axis.dataY;
                    _this.platformChart.loadData(config.name,Axis.dataY);
                } else{//实时
                    if(_this.platformHistory[config.name+'_'+config.type]){
                        _this.platformHistory[config.name+'_'+config.type].shift();
                        _this.platformHistory[config.name+'_'+config.type].push(Axis.dataY[0]);
                        _this.platformChart.loadData(config.name,_this.platformHistory[config.name+'_'+config.type]);
                    }
                }    
            };
            var error=function(e){
                console.log('锅炉协同台加载出错了');
            };
            this.$http.get(config.url).then(success,error);
        },
        getPlatFormHistory:function(){
                for(var i=1;i<=5;i++){
                   var num=i;
                   this.getPlatFormChartData({
                        name:num+'号锅炉用气',
                        type:'history',
                        url:URL+'/guolu/'+num+'/gas/history'
                    }); 
                }
                this.getPlatFormChartData({
                    name:'当前总用气',
                    type:'history',
                    url:URL+'/quanwang/guolu/history'
                });
        },
        getPlatFormReal:function(){
                for(var i=1;i<=5;i++){
                   var num=i;
                   this.getPlatFormChartData({
                        name:num+'号锅炉用气',
                        type:'real',
                        url:URL+'/guolu/'+num+'/gas/realPoint'
                    }); 
                }
                this.getPlatFormChartData({
                    name:'当前总用气',
                    type:'real',
                    url:URL+'/quanwang/guolu/realPoint'
                });
        },
        getCoordination:function(){
            var success=function(res){
                var _this=this;
                this.coordination=res.data;
                if(this.coordination[this.guolu-1].status==1){
                    _this.currentStatus = true;
                }else{
                    _this.currentStatus = false;
                }
                if(this.coordination[this.guolu-1].status==0){
                    _this.currentStatusVal = true;
                }else{
                    _this.currentStatusVal = false;
                }
            };
            var error=function(e){
                console.log('加载右侧协同台出错')

            };
            this.$http.get(URL+'/guolu/xietong').then(success,error)
        },
        getCurrentgas:function(){//协同台当前用气总量
            var success=function(res){
                this.gasCurrent=res.data[1];
            };
            var error=function(e){
                console.log('加载右侧协同台出错当前总用气量出错')

            };
            this.$http.get(URL+'/quanwang/guolu/realPoint').then(success,error)
        },
        initBarChart:function(){
            this.pressBar = new Bar('press_bar',{
                data:'',
                baseOption:barChart
            })
        },
        getBarchart:function(){
            /*左侧绩效柱状图*/
            var _this = this;

            var success = function(res){
                _this.Achievements = res.data;
                _this.pressBar.loadData('数值',_this.Achievements.value)
            };
            var error = function(e){
              console.log('加载绩效图报错')
            };
            this.$http.get(URL+'/guolu/'+this.guolu+'/performance').then(success,error);
        },
        getRealPoint:function(){
            var _this = this;
            var success = function(res){
                _this.fangsanReal=Number(res.data[0][1]).toFixed(2)
            };
            var error  = function(){
                console.log('加载放散开度错误')
            }
            this.$http.get(URL+'/coalgas/fangsan/realPoint').then(success,error)
        }

    }
});
